<?php
// 数据库连接配置  
$servername = "localhost";
$username = "bay";
$password = "bay618618";
$dbname = "bay_iot";

// 创建连接  
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接  
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 处理登录请求  
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $conn->real_escape_string($_POST["username"]);
    $password = $conn->real_escape_string($_POST["password"]);

    // 查询数据库中的用户  
    $user_sql = "SELECT user_id, password FROM user_table WHERE username = '$username'";
    $user_result = $conn->query($user_sql);
    if ($user_result->num_rows == 1)
	{
        // 用户名存在，验证密码  
        $row = $user_result->fetch_assoc();
        if (password_verify($password, $row["password"])) 
		{
            // 密码正确，登录成功  
            session_start();
            $_SESSION["user_id"] = $row["user_id"];
            echo "登录成功" . "<br>";
			$user_id = $row["user_id"];
			echo "用户ID: " . $user_id . "<br>";
			$sql = "SELECT d.* FROM iot_device_table d  
					JOIN user_device_binding_table b ON d.device_id = b.device_id  
					WHERE b.user_id = ?";
			$stmt = $conn->prepare($sql);  
			$stmt->bind_param("i", $user_id); // 绑定用户ID参数  
			$stmt->execute();
			$result = $stmt->get_result();
			if ($result->num_rows > 0) 
			{  
				// 输出设备信息  
				while ($row = $result->fetch_assoc()) 
				{  
					echo "设备ID: " . $row["device_id"] . "<br>";  
					echo "设备名称: " . $row["device_name"] . "<br>"; 
					echo "设备密钥: " . $row["device_secret"] . "<br>";  
					echo "设备类型: " . $row["product_key"] . "<br><br>";  
				}  
			} 
			else 
			{  
				echo "该用户没有绑定任何设备。";  
			}
			$stmt->close();
        } 
		else 
		{
            // 密码错误  
            echo "密码错误";
        }
    } 
	else 
	{
        // 用户名不存在  
        echo "用户名不存在";
    }

    $user_result->close();
    $conn->close();
}
?>